package com.hmall.item.controller;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constabtnts.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
public class ItemController {

    //注入service接口,根据商品id查询商品信息
    @Autowired
    ItemService itemService;

    //注入mq模板对象
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品的数据
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> getItemList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "size", defaultValue = "5") Integer size) {
        return itemService.getItemByPage(page, size);

    }

    @GetMapping("{id}")
    public Item findItemById(@PathVariable("id") Long id) {
        return itemService.findItemById(id);
    }

    @PostMapping
    public void addItem(@RequestBody Item item) {
        itemService.addItem(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        if (status==1){
            //发送消息
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_INSERT_KEY, id);
        }else{
            //发送消息
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_DELETE_KEY, id);
        }
        itemService.updateStatus(id, status);
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        itemService.updateItem(item);

    }


    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        itemService.deleteItem(id);

    }

    /**
     * 扣减库存
     * itemId 商品id  num  商品的数量
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void updateNum(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num) {
        itemService.updateNum(itemId,num);
    }

    /**
     * 将订单状态为5的库存加回来
     * @param itemId 商品id
     * @param num 数量
     */
    @RequestMapping("{itemId}/{num}")
    void updateStock(@PathVariable("itemId") Long itemId,@PathVariable("num") Integer num){
        itemService.updateStock(itemId,num);
    }
}
